package com.example.messageservice.controller;

import com.example.commonutils.R;
import com.example.messageservice.service.MessageService;
import com.example.messageservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/textmessage")
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone){
        //1、拿手机号去redis中查询验证码
        String rPhone = redisTemplate.opsForValue().get(phone);
        //2、验证验证码是否存在
        if (rPhone != null){
            // 存在，直接返回ok
            return R.ok();
        }
        // 不存在,生成验证码
        String code = RandomUtil.getSixBitRandom();
        //调用接口服务，发送短信
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = messageService.sendSmsPhone(phone,map);
        //发送成功验证码存入redis，时效5分钟
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error();
        }
    }
}
